package com.example.taskschedule.infrastructure.monitor;

import com.example.taskschedule.infrastructure.threadPool.StatisticsCollector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.logging.LogLevel;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池监控类
 * 每秒打印线程池状态并更新最大并发数
 * 应为守护线程
 */
@Slf4j
public class ThreadPoolMonitor implements Runnable{
    private final ThreadPoolExecutor threadPool;
    public ThreadPoolMonitor(ThreadPoolExecutor threadPool) {
        this.threadPool = threadPool;
    }
    @Override
    public void run() {
        try {
            while(!Thread.currentThread().isInterrupted()){
                Thread.sleep(1000);
                printThreadPoolStatus();
                updateMaxConcurrentThreads();
            }
        } catch (Exception e) {
            Thread.currentThread().interrupt();
        }
    }
    private void printThreadPoolStatus(){
        log.info("当前线程池状态：");
        log.info("线程池当前线程数量：{}", threadPool.getPoolSize());
        log.info("线程池当前活动线程数量：{}", threadPool.getActiveCount());
        log.info("线程池已完成任务数：{}", threadPool.getCompletedTaskCount());
        log.info("队列中等待任务数量：{}", threadPool.getQueue().size());
        //更新线程数峰值
        StatisticsCollector.updateThreadPeak(threadPool.getPoolSize());
    }
    private void updateMaxConcurrentThreads(){
        StatisticsCollector.updateMaxConcurrentThreads(threadPool.getActiveCount());
    }
}
